<template>
  <div class="tp h-full flex" v-loading="state.loading">
    <Header />

    <Content
      class="flex flex-col flex-1 overflow-hidden"
      bodyClass="flex-1 overflow-hidden flex flex-col"
    >
      <div class="cp flex flex-col h-full">
        <a-flex gap="middle" align="center" class="h-bar">
          <div @click="verificationDrawer(true)">
            <a-flex gap="small" align="center" class="use item">
              <img src="./img/b-ico-1.png" class="icon" alt="" />
              <span class="title">核销</span>
            </a-flex>
          </div>

          <div @click="router.replace('/cashier/index/take-order')">
            <a-flex gap="small" align="center" class="use item">
              <img src="./img/b-ico-2.png" class="icon" alt="" />
              <span class="title">取单</span>
            </a-flex>
          </div>

          <div @click="router.replace('/report/order-list')">
            <a-flex gap="small" align="center" class="use item">
              <img src="./img/b-ico-3.png" class="icon" alt="" />
              <span class="title">订单</span>
            </a-flex>
          </div>

          <div @click="router.replace('/cashier/index/daily-overview')">
            <a-flex gap="small" align="center" class="use item">
              <img src="./img/b-ico-4.png" class="icon" alt="" />
              <span class="title">当日台账</span>
            </a-flex>
          </div>
        </a-flex>

        <div class="m-bar">
          <div
            :class="['v-1', state.memberCode !== '-1' ? 'active' : '']"
            @click="onChangeType('v1')"
          >
            客户
          </div>
          <div
            :class="['v-2', state.memberCode === '-1' ? 'active' : '']"
            @click="onChangeType('v2')"
            >散客</div
          >
        </div>

        <div style="padding: 16px 8px; background-color: #fff; border-top-right-radius: 8px">
          <div :class="['m-body', state.memberCode === '-1' ? 'bg2' : 'bg1']">
            <a-flex align="center" gap="middle">
              <a-avatar
                :size="52"
                :src="OSS_IMG_URL(memberRef.memberWeixinDataBean?.headImgUrl, vipAvatar)"
              />

              <div>
                <a-flex gap="small" align="flex-end">
                  <template v-if="state.memberCode === '-1'">
                    <span class="name">散客</span>
                  </template>
                  <template v-else>
                    <span class="name"> {{ memberRef.realName }}</span>
                    <!-- <span class="tag" style="margin-bottom: 2px">{{
                      getLabel(memberSources, memberRef.memberSource) || '--'
                    }}</span> -->
                    <span class="tag" style="margin-bottom: 2px">
                      {{
                        memberRef.memberType == 1
                          ? '新客'
                          : memberRef.memberType == 2
                            ? '体验客'
                            : memberRef.memberType == 3
                              ? '会员'
                              : memberRef.memberType
                      }}
                    </span>
                  </template>
                </a-flex>
                <div v-if="state.memberCode !== '-1'" class="d-regular mobile">
                  {{ memberRef.mobile?.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3') }}
                </div>
              </div>

              <div class="fill"></div>

              <div v-if="state.memberCode !== '-1'" class="tag_display">
                <span class="tag_context">本月消费</span
                ><span class="tag_quantita"
                  ><span class="tag_num">{{ pendingOrderList.monthComeQty || 0 }}</span
                  >次</span
                >
              </div>

              <div class="use replace" @click="onSelectMember">替换</div>
            </a-flex>
          </div>
        </div>

        <div
          class="card flex-1 overflow-hidden"
          style="border-top-left-radius: 0; border-top-right-radius: 0; padding-top: 0"
        >
          <a-row :gutter="24" class="h-full">
            <a-col :span="9" class="h-full">
              <a-flex align="center" gap="16" class="list-search">
                <a-input v-model:value="state.serachCache" :disabled="searchLoading" @pressEnter="cateSearch" placeholder="请输入产品/疗程/卡项名称" class="search-input">
                  <template #prefix>
                    <SearchOutlined style="font-size: 16px; color: '#CED5DF'"/>
                  </template>
                </a-input>
                <a-button type="primary" class="search-btn" :loading="searchLoading" @click="cateSearch">搜索</a-button>
              </a-flex>
              <a-tabs v-model:activeKey="state.search.cateType" type="line" class="overflow-hidden u-tabs">
                <a-tab-pane v-for="o in state.proCategoryTypeN" :key="o.value" :tab="o.label" class="overflow-auto h-full">
                  <template v-if="o.value === 'V'">
                    <div v-for="(a, i) in [state.V.cardTimesPack, state.V.cardMoneyPack]" :key="i">
                      <div v-for="o in a" :key="o.cardNo" class="card-block">
                        <a-flex class="head" gap="small" align="center" justify="space-between">
                          <div class="title">{{ o.cardName }}</div>
                          <div class="cursor-pointer" @click.stop="onCardDetail(o)"
                            ><span class="label">到期时间：</span>
                            <span v-if="o.expireTime === null && o.validType === '20'">{{
                              getValidDesc(o)
                            }}</span
                            >&nbsp;
                            <span
                              class="time"
                              v-else-if="
                                o.validType === '30' || o.validType === '20' || o.validType === '10'
                              "
                              >{{
                                o.expireTime ? dayjs(o.expireTime).format('YYYY-MM-DD') : '--'
                              }}</span
                            >&nbsp;
                            <span v-else-if="o.validType === '40'">永久有效</span>
                            <!--                            &nbsp;-->
                            <!-- <span class="time" v-else-if="!o.expireTime === null">{{
                              o.expireTime ? dayjs(o.expireTime).format('YYYY-MM-DD') : '--'
                            }}</span> -->
                            <!-- <span class="time" v-if="o.validType != '40'">{{
                              o.expireTime ? dayjs(o.expireTime).format('YYYY-MM-DD') : '--'
                            }}</span>
                             <span class="time">{{ getValidDesc(o) }}</span> -->
                            <!--                            <span v-else>永久有效</span>&nbsp;-->

                            <span class="rightqutlined_detail"><RightOutlined /></span>
                          </div>
                        </a-flex>
                        <div class="body">
                          <template v-if="o.cardSubType === '201'">
                            <!--有限次卡-->
                            <a-flex gap="small" wrap="wrap">
                              <!-- 商品 -->
                              <card-goods :card-times-pack-item="o"></card-goods>
                              <!--赠送-->
                              <card-give :card-times-pack-item="o" />
                            </a-flex>
                          </template>
                          <template v-else-if="o.cardSubType === '202'">
                            <!-- 不限次卡 -->
                            <div class="cg-label">以下商品不限次数</div>
                            <a-flex gap="small" wrap="wrap">
                              <!-- 商品 -->
                              <card-goods :card-times-pack-item="o"></card-goods>
                            </a-flex>

                            <!--赠送-->
                            <a-flex gap="small" wrap="wrap">
                              <card-give :card-times-pack-item="o" />
                            </a-flex>
                          </template>
                          <template v-else-if="o.cardSubType === '203'">
                            <!-- 通卡 -->
                            <div class="cg-label">
                              以下商品共剩{{ getCardGoodsRemainQty({ cardTimesPackItem: o }) }}次
                            </div>
                            <a-flex gap="small" wrap="wrap">
                              <!-- 商品 -->
                              <card-goods :card-times-pack-item="o"></card-goods>
                            </a-flex>

                            <!--赠送-->
                            <a-flex gap="small" wrap="wrap">
                              <card-give :card-times-pack-item="o" />
                            </a-flex>
                          </template>
                          <template v-else-if="o.cardSubType === '101'">
                            <!-- 金额卡 -->
                            <card-amount :card-money-pack-item="o" />

                            <!--赠送-->
                            <a-flex gap="small" wrap="wrap">
                              <card-give :card-times-pack-item="o" />
                            </a-flex>
                          </template>
                        </div>
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <a-flex gap="small" wrap="wrap" class="cate-sub">
                      <div
                        :class="[
                          'use',
                          'cell',
                          state[o.value].cateCode === null ? 'active' : 'tacit',
                        ]"
                        @click="state[o.value].cateCode = null"
                        >全部
                      </div>
                      <div
                        v-for="z in getCateSubList(o.value)"
                        :key="z.cateCode"
                        :class="[
                          'use',
                          'cell',
                          state[o.value].cateCode === z.cateCode ? 'active' : 'tacit',
                        ]"
                        @click="state[o.value].cateCode = z.cateCode"
                      >
                        {{ z.cateSubName }}
                      </div>

                      <div class="btn" v-if="getCateSubAll(o.value).length > state.foldMinCount">
                        <a-button
                          v-if="state[o.value].hasFold"
                          type="link"
                          size="small"
                          :icon="h(CaretDownOutlined)"
                          @click="state[o.value].hasFold = false"
                          >展开
                        </a-button>
                        <a-button
                          v-else
                          type="link"
                          size="small"
                          :icon="h(CaretUpOutlined)"
                          @click="state[o.value].hasFold = true"
                          >收起
                        </a-button>
                      </div>
                    </a-flex>
                    <div class="p-list">
                      <template v-if="state[o.value].pager.list?.length > 0">
                        <div
                          :class="[
                            'p-card',
                            isExistProductByCart(o.value, item) && 'active tri-active',
                          ]"
                          v-for="item in state[o.value].pager.list"
                          :key="item.goodsSn"
                          @click="
                            !isExistProductByCart(o.value, item) &&
                              onAddProduct2Cart(o.value, item, { cardMoneyId: state.consumption })
                          "
                        >
                          <a-flex gap="middle">
                            <a-image
                              :width="64"
                              :height="64"
                              :src="OSS_IMG_URL(item.cardImage || item.goodsImage)"
                              :fallback="imgErrSrc"
                            />

                            <a-flex class="fill right" vertical :gap="2">
                              <div class="cn-medium title">
                                <div>{{ item.cardName || item.goodsName }}</div>
                              </div>
                              <div class="fill"></div>
                              <a-flex gap="small" justify="space-between">
                                <div class="price"
                                  ><span class="d-regular value">{{ item.salePrice }}</span
                                  ><span class="unit">元</span></div
                                >
                                <div class="desc" v-if="o.value === 'P'">
                                  {{ item.specs }}
                                </div>
                                <div class="desc" v-else-if="o.value === 'S'">
                                  {{ item.duration }}分钟
                                </div>
                                <div class="desc" v-else-if="o.value === 'C'">
                                  {{
                                    getChildrenLabel(proCardType, item.cardType, item.cardSubType)
                                  }}
                                </div>
                              </a-flex>
                            </a-flex>

                            <div class="tri-symbol"></div>
                            <div v-if="isExistProductByCart(o.value, item)" class="tri-checked">
                              <CheckOutlined />
                            </div>

                            <div class="add jump_details">
                              <div class="icon_jump_details">
                                <a-button type="link" @click="jumpProductDetails(o.value, item)"
                                  >详情</a-button
                                >
                              </div>
                              <div
                                ><img
                                  src="./img/add-1.png"
                                  class="use icon"
                                  @click="
                                    onAddProduct2Cart(o.value, item, {
                                      cardMoneyId: state.consumption,
                                    })
                                  "
                                  alt=""
                              /></div>
                            </div>
                          </a-flex>
                        </div>

                        <div class="pagination">
                          <a-pagination
                            :default-page-size="state.pageSize"
                            size="small"
                            v-model:current="state[o.value].pager.currentPage"
                            :total="state[o.value].pager.totalCount"
                            show-size-changer
                            @showSizeChange="onShowSizeChange"
                          />
                        </div>
                      </template>
                      <a-empty v-else />
                    </div>
                  </template>
                </a-tab-pane>
              </a-tabs>
            </a-col>
            <a-col
              :span="15"
              style="
                background: rgba(255, 223, 231, 0.06);
                border-radius: 4px;
                border: 1px solid #ffdfe7;
                padding: 16px;
              "
              class="overflow-auto h-full"
            >
              <div class="c-title" style="margin-bottom: 6px"> 已选商品 </div>
              <template v-if="shopCartRef.length">
                <div
                  v-for="(item, index) in shopCartRef"
                  :key="`${item.id + Math.random()}`"
                  class="cart-item"
                >
                  <div class="header">
                    <a-checkbox
                      :disabled="item.disabledGive"
                      v-model:checked="item.isGive"
                      @change="onToggleGive(item, $event)"
                      style="color: #6d414c"
                      >设为赠送权益
                    </a-checkbox>
                  </div>
                  <a-row align="middle">
                    <a-col :span="22">
                      <div class="ci-body">
                        <div>
                          <a-flex
                            gap="small"
                            class="pro-name"
                            align="center"
                            justify="space-between"
                          >
                            <div class="title">{{ item.title }}</div>
                            <div class="number">
                              <a-input-number
                                :value="item.qty"
                                :controls="true"
                                :min="1"
                                :max="9999999"
                                :precision="0"
                                @change="onCartQtyChange(item, $event, { calc: true })"
                              />
                            </div>
                          </a-flex>
                        </div>

                        <div>
                          <a-row :gutter="12" class="ct-row">
                            <a-col :span="18">
                              <a-flex gap="middle">
                                <div class="fill">
                                  <div class="c-label">卡种</div>
                                  <a-input
                                    v-if="item.isGive || item.disabledGive"
                                    :disabled="true"
                                    :default-value="item.parentTitle || '暂无可用卡片'"
                                  ></a-input>
                                  <a-input
                                    v-else-if="
                                      item.primitive.proItem.cardType === '100' ||
                                      state.memberCode === '-1'
                                    "
                                    :disabled="true"
                                    default-value="暂无可用卡片"
                                  ></a-input>

                                  <a-select
                                    v-else
                                    v-model:value="item.cardMoneyId"
                                    placeholder="请选择卡项"
                                    :options="cardMoneyRef"
                                    :allow-clear="true"
                                    @change="calcPriceByCart()"
                                    style="width: 100%"
                                  >
                                  </a-select>
                                </div>
                                <div class="fill">
                                  <div class="c-label">美容师</div>
                                  <a-select
                                    :value="item.beauticianList"
                                    mode="multiple"
                                    :token-separators="[',']"
                                    placeholder="请选择美容师"
                                    @change="selectByCart(item, $event, index)"
                                    :options="beauticianRef"
                                    style="width: 100%"
                                    :showSearch="false"
                                  ></a-select>
                                </div>
                              </a-flex>
                              <!-- 1111111 -->
                              <div
                                v-if="!!item.cardMoneyId"
                                style="font-size: 14px; color: #666666; margin-top: 5px"
                              >
                                余额: {{ item.moneyLastAmount }}&nbsp;&nbsp;
                                {{ getProductDiscount(getCardMoneyPackItemByCart(item)) }}
                              </div>
                            </a-col>

                            <a-col :span="6" style="text-align: right">
                              <div
                                style="
                                  font-weight: 400;
                                  font-size: 14px;
                                  color: #999999;
                                  text-decoration: line-through;
                                "
                              >
                                <span>零售价</span>&nbsp;&nbsp;<span>¥&nbsp;</span
                                ><span class="d-regular">{{ item.retailAmount || 0 }}</span>
                              </div>
                              <div style="margin-top: 8px">
                                <span style="font-size: 14px; color: #6d414c">折后价</span
                                >&nbsp;&nbsp;<span style="font-weight: 500; color: #6d414c"
                                  >¥&nbsp;</span
                                >
                                <span style="font-weight: 500; font-size: 20px; color: #6d4141">{{
                                  item.discountAfterAmount || 0
                                }}</span>
                              </div>

                              <div style="margin-top: 8px">
                                <span style="font-size: 14px; color: #6d414c">-</span
                                >&nbsp;&nbsp;<span style="font-weight: 500; color: #6d414c"
                                  >¥&nbsp;</span
                                >
                                <span style="font-weight: 400; font-size: 16px; color: #6d414c">{{
                                  (item.disabledGive
                                    ? item.discountAfterAmount
                                    : item.moneyDeductionAmount) || 0
                                }}</span>
                              </div>
                            </a-col>
                          </a-row>

                          <div
                            style="
                              border-top: 1px solid #f7e4e9;
                              text-align: right;
                              padding-top: 8px;
                              margin-top: 8px;
                            "
                          >
                            <span style="font-size: 14px; color: #6d414c">应付</span
                            >&nbsp;&nbsp;<span
                              style="font-weight: 500; color: #6d414c; font-size: 14px"
                              >¥&nbsp;</span
                            >
                            <!-- <span style="font-weight: 500; font-size: 20px; color: #6d414c">{{
                              item.payableAmount
                            }}</span> -->
                            <span style="font-weight: 500; font-size: 20px; color: #6d414c">
                              {{ item.payableAmount || 0 }}
                            </span>
                          </div>
                        </div>
                      </div>
                    </a-col>

                    <a-col :span="2">
                      <div class="delete" @click="onDeleteCartItemFn(item)">
                        <div class="icon">
                          <DeleteOutlined />
                        </div>
                        <div class="label">删除</div>
                      </div>
                    </a-col>
                  </a-row>
                </div>
              </template>
              <div
                v-else
                style="
                  background: #fff;
                  border-radius: 8px;
                  border: 1px dashed #ce7b90;
                  font-weight: 400;
                  font-size: 16px;
                  color: #eb6485;
                  height: 150px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                请先从左侧选择权益或商品
              </div>

              <div v-if="shopConsumeRef && shopConsumeRef.length">
                <a-row :gutter="8" style="margin: 0 6px 12px 0">
                  <a-col :span="12" class="c-title">配料明细</a-col>
                  <a-col :span="12" style="text-align: right">
                    <a-button @click="onAddConsume" type="primary">添加配料 </a-button>
                  </a-col>
                </a-row>

                <div
                  style="
                    background: rgba(255, 223, 231, 0.06);
                    border-radius: 4px;
                    border: 1px solid #ffdfe7;
                    padding: 12px;
                  "
                >
                  <BasicTable
                    @register="registerTableConsume"
                    :dataSource="shopConsumeRef"
                    style="padding: 0"
                    :scroll="{ y: 320 }"
                  >
                    <template #proImg="{ record }">
                      <pro-img-cell
                        :mode="record.mode"
                        :src="record.goodsImage"
                        :title="record.goodsName"
                      />
                    </template>

                    <template #stock="{ record }">
                      <a-flex gap="small" align="center">
                        <a-checkbox
                          v-model:checked="record.isSelected"
                          style="color: #333"
                          @change="record.csmValue = $event.target.checked ? 0 : null"
                          >领用新产品
                        </a-checkbox>

                        <a-input-number
                          :disabled="!record.isSelected"
                          v-model:value="record.csmValue"
                          :controls="true"
                          :min="0"
                          :max="9999999"
                          :precision="0"
                          style="width: 60px !important"
                          :addon-after="record.saleUnit"
                        />
                      </a-flex>
                    </template>

                    <template #action="{ record }">
                      <TableAction
                        :divider="true"
                        :actions="[
                          {
                            color: 'success',
                            label: '删除',
                            popConfirm: {
                              title: '您确定要删除吗',
                              confirm: () => onDeleteConsume(record),
                            },
                          },
                        ]"
                      />
                    </template>
                  </BasicTable>
                </div>
              </div>
              <!-- 111111111-->

              <div class="c-title"> 其他信息 </div>
              <div style="padding: 12px 0">
                <a-row :gutter="[24, 12]" align="middle">
                  <a-col :span="3" class="f-label" style="text-align: right"> 下单时间 </a-col>
                  <a-col :span="8">
                    <a-date-picker
                      v-model:value="cartInfoRef.addTime"
                      :show-time="true"
                      :disabled-date="(value) => !dayjs(value).isSameOrBefore(dayjs())"
                    />
                  </a-col>
                  <a-col :span="13"></a-col>

                  <a-col :span="3" class="f-label" style="text-align: right"> 优惠金额 </a-col>
                  <a-col :span="8">
                    <a-input-number
                      v-model:value="cartInfoRef.discountAmount"
                      :controls="true"
                      :min="0"
                      :max="9999999"
                      :precision="2"
                      addon-after="元"
                      @change="handleDiscountChange"
                    />
                  </a-col>
                  <a-col :span="13"></a-col>

                  <a-col :span="3" class="f-label" style="text-align: right"> 备注 </a-col>
                  <a-col :span="16">
                    <a-textarea v-model:value="cartInfoRef.remarks" show-count :maxlength="200" />
                  </a-col>
                  <a-col :span="5"></a-col>
                </a-row>
              </div>
            </a-col>
          </a-row>
        </div>
      </div>
    </Content>

    <Footer>
      <a-flex align="center" justify="center" gap="middle" class="f-body">
        <div
          ><span style="font-weight: 400; font-size: 14px; color: #6d414c"
            >已选{{ getCartQtyTotal() }}件&nbsp;&nbsp;合计&nbsp;</span
          >
          <span style="font-weight: 400; color: #6d414c">¥&nbsp;</span>
          <span style="font-weight: 400; font-size: 20px; color: #6d414c">{{
            getCartPayableAmount()
          }}</span>
        </div>

        <div>
          <a-button danger @click="onSavePendingOrder({ showMsg: true })">挂单</a-button>
        </div>

        <div>
          <a-button type="primary" @click="onPayment()">提交订单</a-button>
        </div>
      </a-flex>
    </Footer>

    <SelectMember @register="registerMember" @complete="onMember" />
    <Consume @register="registerConsume" @complete="onConsumeComplete" />
    <Payment @register="registerPayment" />
    <Verification @register="registerVerification" />
    <Detail @register="registerDetail" @complete="onSearch" />
    <cardDetail @register="registerCardDetail" @complete="onSearch" />
  </div>
</template>

<script setup>
  import { defineOptions, h, onMounted, reactive, ref, watch, provide, computed } from 'vue';
  import { SearchOutlined } from '@ant-design/icons-vue'
  import {
    CaretDownOutlined,
    CaretUpOutlined,
    CheckOutlined,
    DeleteOutlined,
    RightOutlined,
  } from '@ant-design/icons-vue';
  import { useMessage } from '@/hooks/web/useMessage';

  import Header from '@/widget/header.vue';
  import Content from '@/widget/content.vue';
  import { GET, PAGE, POST } from '@/api/http';
  import { getValidDesc } from '../product/list/util';
  import {
    getChildrenLabel,
    getLabel,
    imgErrSrc,
    memberSources,
    OSS_IMG_URL,
    proCardType,
    proCategoryType2,
    proCategoryType3,
  } from '@/api/ds';
  import { useRoute, useRouter } from 'vue-router';

  import SelectMember from './select-member.vue';
  import { useDrawer } from '@/components/Drawer';
  import { copy, exist } from '@/api/util.js';
  import CardGive from './card-give.vue';
  import CardGoods from './card-goods.vue';
  import CardAmount from './card-amount.vue';
  import Detail from '../product/list/detail.vue';
  import cardDetail from '../member/card-detail.vue';
  import {
    calcPriceByCart,
    clearCart,
    getCardGoodsRemainQty,
    getCardMoneyPackItemByCart,
    getCartDiscountAmount,
    getCartPayableAmount,
    getCartQtyTotal,
    selectByCart,
    getDeductionAmount,
    initCart,
    isExistByCart,
    isExistProductByCart,
    loadBeautician,
    loadPendingData,
    onAddProduct2Cart,
    onCartQtyChange,
    onConsumeComplete,
    onDeleteCartItem,
    onDeleteConsume,
    onToggleGive,
    savePendingOrder,
  } from './cart.js';
  import { getProductDiscount } from '@/views/member/util.js';
  import vipAvatar from '@/assets/images/vip-avatar.png';
  import { BasicTable, TableAction, useTable } from '@/components/Table';
  import ProImgCell from '@/widget/pro-img-cell.vue';
  import dayjs from 'dayjs';

  import Consume from './consume.vue';
  import Payment from './payment.vue';
  import Verification from './verification.vue';
  import Footer from '@/widget/footer.vue';
  import { omit } from 'lodash-es';

  defineOptions({ name: 'CashierIndex' });

  const { createMessage } = useMessage();
  const [registerMember, { openDrawer: memberDrawer }] = useDrawer();
  const [registerConsume, { openDrawer: consumeDrawer }] = useDrawer();
  const [registerPayment, { openDrawer: paymentDrawer, closeDrawer: closePayment }] = useDrawer();
  const [registerVerification, { openDrawer: verificationDrawer }] = useDrawer();
  const [registerDetail, { openDrawer: detailDrawer }] = useDrawer();
  const [registerCardDetail, { openDrawer: detailCardDrawer }] = useDrawer();

  const route = useRoute(),
    router = useRouter();

  let {
    memberCode = null,
    takeId = null,
    workDate = null,
    cardNo = null,
    consumption = null,
    // 耗卡的类型
    cardSubType = null,
  } = route.query;
  memberCode ||= '-1';
  console.log(route.query);
  let { cardMoneyRef, cartInfoRef, shopCartRef, shopConsumeRef, beauticianRef } = initCart();

  const searchLoading = ref(false)
  // 用来计算搜索多个接口次数，等于除权益外tab菜单数仍未搜索到数据则关闭loading状态
  const cateSearchNum = ref(0) 
  const state = reactive({
    loading: false,
    memberCode,
    takeId,
    consumption,
    workDate,
    cardNo,
    cardSubType,
    proCategoryTypeN: [],

    serachCache: '',
    search: {
      selectStatus: 0,
      cateType: 'P',
      goodsName: null,
    },

    foldMinCount: 6,
    pageSize: 10,

    V: {
      selectedSn: new Set(),
      selected: [],
      hasFold: true,
      cateCode: null,
      version: null,
      cardTimesPack: [],
      cardMoneyPack: [],
      pager: {
        currentPage: 0,
      },
    },

    P: {
      selectedSn: new Set(),
      selected: [],
      hasFold: true,
      cateCode: null,
      version: null,
      pager: {
        currentPage: 0,
      },
    },
    S: {
      selectedSn: new Set(),
      selected: [],
      hasFold: true,
      cateCode: null,
      version: null,
      pager: {
        currentPage: 0,
      },
    },
    C: {
      selectedSn: new Set(),
      selected: [],
      hasFold: true,
      cateCode: null,
      version: null,
      pager: {
        currentPage: 0,
      },
    },

    categoryList: [],
  });

  const memberRef = ref({});
  const pendingOrderList = ref({});

  const maxDiscountAmount = computed(() => {
    return (
      shopCartRef.value.reduce(
        (acc, cv) =>
          acc +
          (cv.disabledGive
            ? 0
            : cv.discountAfterAmountWithoutDeduction - cv.moneyDeductionAmount || 0),
        0,
      ) ?? 0
    );
  });

  const onDeleteCartItemFn = (item) => {
    onDeleteCartItem(item);
    console.log(shopConsumeRef.value, 'shopConsumeRef');
    shopConsumeRef.value = [...shopConsumeRef.value];
    tableRef.reload();
  };

  const [registerTableConsume, tableRef] = useTable({
    columns: [
      {
        title: '产品名称',
        dataIndex: 'goodsName',
        ellipsis: false,
        width: '280px',
        slots: { customRender: 'proImg' },
      },

      {
        title: '库存使用',
        dataIndex: 'isSelected',
        ellipsis: false,
        slots: { customRender: 'stock' },
      },
    ],
    pagination: false,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
    actionColumn: {
      title: '操作',
      align: 'center',
      width: 90,
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
  });

  onMounted(async () => {
    const { memberCode } = state;

    if (memberCode === '-1') {
      onSelectMember();
    }

    onSearch();
    await loadBeautician();

    if (route.query.takeId) {
      state.takeId = route.query.takeId;
      router.replace({ query: omit(route.query, 'takeId') });
    }
  });

  async function onToggleFold({ memberCode }) {
    pendingOrderList.value = (await GET('/membership/getMemberBaseInfo', { memberCode })) ?? {};
  }

  function onSelectMember() {
    state.cardNo = null;
    memberDrawer(true, {});
  }

  const onChangeType = (type) => {
    if (state.memberCode === '-1') {
      if (type === 'v1') {
        onSelectMember();
      }
    } else {
      if (type === 'v2') {
        state.cardNo = null;
        state.memberCode = '-1';
      }
    }
  };

  function onAddConsume() {
    consumeDrawer(true, { consumeList: copy(shopConsumeRef.value) });
  }

  async function onMember({ memberCode, takeId }) {
    console.log(memberCode);
    state.memberCode = memberCode;
    state.takeId = takeId;
  }

  function onPayment() {
    const { memberCode } = state;

    if (getCartDiscountAmount() > maxDiscountAmount.value) {
      createMessage.error('优惠金额不能大于应付金额');
      return;
    }

    const allArraysHaveValues = shopCartRef._rawValue.every((obj) => obj.beauticianList.length > 0);

    if (!allArraysHaveValues) {
      createMessage.error('请选择美容师');
    } else {
      paymentDrawer(true, {
        memberCode,
        getCartPayableAmount,
        updateDefaultTotalFee() {
          return getCartPayableAmount();
        },
        discountAfterAmount: shopCartRef.value.reduce(
          (acc, item) =>
            acc + (item.disabledGive ? item.discountAfterAmount : item.moneyDeductionAmount),
          0,
        ),
      });
    }
  }

  function jumpProductDetails(value, data) {
    detailDrawer(true, { choose: false, cateType: value, record: data });
  }

  function onCardDetail(row) {
    detailCardDrawer(true, { choose: false, memberCode: row.memberCode, record: row });
  }

  watch(
    () => `${state.memberCode},${state.takeId}`,
    async () => {
      const { memberCode, takeId, workDate, cardNo, cardSubType } = state;
      console.log(memberCode);
      state.proCategoryTypeN =
        memberCode === '-1' ? proCategoryType2.filter((o) => o.value !== 'C') : proCategoryType3;

      if (cardNo != null) {
        state.search.cateType = cardSubType === '101' ? 'P' : 'V';
      } else {
        state.search.cateType = memberCode === '-1' ? 'P' : 'V';
      }

      clearCart();
      memberRef.value =
        memberCode === '-1'
          ? {}
          : (await GET('/membership/getMemberBaseInfo', { memberCode })) ?? {};

      onToggleFold({ memberCode: memberRef.value.memberCode });

      //加载客户权益
      Object.assign(state.V, { cardTimesPack: [], cardMoneyPack: [] });
      if (memberCode !== '-1') {
        try {
          state.loading = true;

          const { list } = await PAGE('/card/getUserCardList')({
            memberCode,
            currentPage: 1,
            pageSize: 10,
          });
          console.log(list);
          let { cardTimesPack, cardMoneyPack } = list?.[0] ?? {};

          const effective = [2];
          cardTimesPack =
            cardTimesPack?.filter(
              (o) =>
                exist(o.expireFlag, effective) &&
                ((o.cardSubType !== '201' &&
                  getCardGoodsRemainQty({ cardTimesPackItem: o }) > 0 &&
                  (o.cardTimesPackItem?.some(
                    (d) =>
                      getCardGoodsRemainQty({ cardTimesPackItem: o, cardTimesGoodsItem: d }) > 0,
                  ) ??
                    true)) ||
                  (o.memberBenefitsBeanList?.some((d) => d.benefitsQty > 0) ?? true)),
            ) ?? [];
          cardMoneyPack = cardMoneyPack?.filter((o) => exist(o.expireFlag, effective)) ?? [];

          //金额卡项
          cardMoneyRef.value = cardMoneyPack.map((o) => ({ ...o, value: o.id, label: o.cardName }));

          Object.assign(state.V, { cardTimesPack, cardMoneyPack });

          if (!!takeId) {
            //加载挂单
            await loadPendingData({ takeId, workDate });
          }
        } finally {
          state.loading = false;
        }
      }
    },
    { immediate: true },
  );

  function getCateWatch(cateType) {
    const target = state[cateType];
    return  `${target.cateCode || ''}-${target.pager.currentPage || 0}-${target.version || ''}`;
  }

  watch(
    () => cartInfoRef.value.discountAmount,
    () => {
      calcPriceByCart();
    },
  );

  watch(
    () => getCateWatch('P'),
    () => doPager('P'),
  );
  watch(
    () => getCateWatch('S'),
    () => doPager('S'),
  );
  watch(
    () => getCateWatch('C'),
    () => doPager('C'),
  );

  function getCateSubAll(cateType) {
    return state.categoryList.filter((z) => z.cateType === cateType);
  }

  function getCateSubList(cateType) {
    const list = getCateSubAll(cateType);
    return state[cateType].hasFold ? list.slice(0, state.foldMinCount) : list;
  }

  function onSearch() {
    doCategoryList();
  }

  function doCategoryList() {
    const { P, S, C } = state;

    POST('/product/libCategoryStoreListAll', { status: 1 }).then((list) => {
      list ||= [];

      //附加卡项分类
      list.push(
        ...proCardType.map((o) => ({
          ...o,
          cateType: 'C',
          cateCode: o.value,
          cateSubName: o.label,
        })),
      );

      state.categoryList = list;

      [P, S, C].forEach((target) => {
        target.cateCode = null;
        target.pager.currentPage = 1;
        target.version = Math.random();
      });
    });
  }

  function doPager(cateType) {
    const { goodsName } = state.search;
    const { [cateType]: target, pageSize } = state,
      { cateCode, pager } = target,
      { currentPage } = pager;
    const url =
      cateType === 'P'
        ? '/product/productStoreList'
        : cateType === 'S'
          ? '/product/serviceStoreList'
          : '/card/getCardBatchData';
    if (cateType === 'C') {
      PAGE(url)({ cardName: goodsName, cardType: cateCode, status: 1, currentPage, pageSize }).then(
        (result) => {
          result?.list?.forEach((o) => {
            //统一命名
            const { cardName: goodsName, batchNo: goodsSn } = o;
            Object.assign(o, { goodsName, goodsSn });
          });
          if (!result?.currentPage && result) delete result.currentPage
          Object.assign(state[cateType].pager, result ?? { list: [], totalCount: 0 })
          getSearchResut(result, cateType)
        },
      ).catch(e => {  searchLoading.value = false })
    } else {
      PAGE(url)({
        goodsName,
        thirdCateCode: cateCode,
        currentPage,
        status: 1,
        pageSize,
      }).then((result) => {
        if (!result?.currentPage && result) delete result.currentPage
        Object.assign(state[cateType].pager, result ?? { list: [], totalCount: 0 })
        getSearchResut(result, cateType)
      }).catch(e => {  searchLoading.value = false })
    }
  }

  function onShowSizeChange(current, size) {
    state.pageSize = size;
    doPager(state.search.cateType);
  }

  function handleDiscountChange(e) {
    if (e > maxDiscountAmount.value) {
      createMessage.error('优惠金额不能大于应付金额');
    }
  }

  provide('onSavePendingOrder', { onSavePendingOrder });

  async function onSavePendingOrder(opt) {
    const { showMsg = false } = opt ?? {};
    const { memberCode, takeId, workDate } = state;

    if (memberCode === '-1') {
      if (showMsg) {
        createMessage.error('散客不能挂单');
      }
      return closePayment?.();
    }

    await savePendingOrder({ memberInfo: memberRef.value, takeId, workDate });

    createMessage.success('已挂单');
    router.replace('/cashier/index/take-order');
  }
  
  
  // 搜索
  function cateSearch() {
    searchLoading.value = true
    let cardTypes = state.proCategoryTypeN.filter(item => item.value !== 'V').map(item => item.value)
    state.search.goodsName = state.serachCache
    cateSearchNum.value = 0 // 每次搜索重置匹配次数
    cardTypes.forEach(type => {
      state[type].pager.currentPage = 1
      state[type].version = Math.random();
    })
  }
  // 获取搜索结果切换卡
  function getSearchResut(result, cateType) {
    let cardTypes = state.proCategoryTypeN.filter(item => item.value !== 'V').map(item => item.value)
    // if ( result?.list?.length && searchLoading.value ) {
    //   searchLoading.value = false
    //   state.search.cateType = cateType
    // } else 
    if( cateSearchNum.value === cardTypes.length - 1 ) {
      searchLoading.value = false
    }
    cateSearchNum.value++
  }
</script>

<style lang="less" scoped>
  .cart-item {
    .header {
      background-image: url('./img/cart-item-h-bg.png');
      background-repeat: no-repeat;
      background-position: left top;
      background-size: contain;
      height: 36px;
      margin-left: 0;

      display: flex;
      flex-direction: column;
      justify-content: center;
      padding-left: 12px;
    }

    .ci-body {
      background: #ffffff;
      box-shadow: 0 1px 6px 0 rgba(229, 197, 197, 0.5);
      border-radius: 0 4px 4px 4px;
      padding: 0 12px 12px 12px;
      margin-bottom: 18px;
    }

    .delete {
      padding-left: 24px;
      color: #eb6485;

      .icon {
        font-size: 26px;
      }

      .label {
        margin-top: 2px;
        font-size: 12px;
      }
    }

    .pro-name {
      padding: 8px 12px;
      margin: 0 -12px;
      background: #f9f9f9;
      box-shadow: inset 0px -1px 0px 0px #fff0f0;
      border-radius: 4px 4px 0 0;
      margin-bottom: 8px;

      .title {
        font-weight: 600;
        font-size: 18px;
        color: #c95e78;
      }

      .number {
        width: 120px;
      }
    }

    .ct-row {
      .c-label {
        font-weight: 400;
        font-size: 14px;
        color: #6d414c;
        padding-bottom: 6px;
      }
    }
  }

  .rightqutlined_detail {
    cursor: pointer;
  }
</style>

<style lang="less" scoped>
  .card-block {
    margin: 8px 0;

    .head {
      padding: 0 8px;
      background-image: url('./img/card-h-bg.png');
      background-repeat: no-repeat;
      background-position: center top;
      background-size: cover;
      height: 44px;

      .title {
        font-size: 14px;
        color: #6d414c;
      }

      .label {
        font-size: 12px;
        color: #6d414c;
      }

      .time {
        font-weight: 500;
        font-size: 14px;
        color: #6d414c;
      }
    }

    .body {
      margin: 0 12px;
      padding: 8px;
      background: #fff9f9;
      box-shadow: inset 0px -1px 0px 0px #ffe6ee;
      border-radius: 0 0 4px 4px;
    }

    .cg-label {
      margin-top: 8px;
      font-weight: 400;
      font-size: 12px;
      color: #333;
    }
  }
</style>

<style lang="less" scoped>
  .h-bar {
    margin-bottom: 12px;

    .item {
      background: #fff6f8;
      border-radius: 8px;
      border: 1px solid #f2a8ba;
      padding: 4px 12px;

      .icon {
        width: 22px;
        object-fit: contain;
      }

      .title {
        font-weight: 400;
        font-size: 15px;
        color: #eb6485;
      }
    }
  }

  .m-bar {
    position: relative;
    display: flex;
    flex-direction: row;

    .v-1,
    .v-2 {
      position: relative;
      background: #fff;
      font-weight: 500;
      font-size: 16px;
      color: #666666;
      cursor: pointer;

      height: 40px;

      display: flex;
      align-items: center;
      justify-content: center;
    }

    .active {
      border-radius: 8px 8px 0 0 !important;
      background: #f3c5d2;
      color: #fff;
      z-index: 2;
    }

    .v-1 {
      width: 130px;
      border-radius: 8px 8px 0 0;
    }

    .v-2 {
      width: 139px;
      border-radius: 0 8px 0 0;
      margin-left: -9px;
    }
  }

  .bg1 {
    background-image: url('./img/m-body-bg1.png');
  }

  .bg2 {
    background-image: url('./img/m-body-bg2.png');
  }

  .m-body {
    background-repeat: no-repeat;
    background-position: center top;
    background-size: cover;
    height: 86px;

    padding: 12px 12px 8px 16px;

    .name {
      font-weight: 500;
      font-size: 18px;
      color: #ce7b90;
    }

    .tag {
      background: linear-gradient(90deg, #f79dbb 0%, #eb6485 100%);
      border-radius: 32px;
      font-size: 11px;
      color: #ffffff;
      padding: 2px 6px;
    }

    .mobile {
      font-weight: 400;
      font-size: 14px;
      color: #ce7b90;
      margin-top: 6px;
    }

    .tag_display {
      font-size: 12px;
      .tag_quantita {
        color: #ec6d8c;
        .tag_num {
          letter-spacing: 2px;
          font-size: 30px;
        }
      }
    }

    .replace {
      width: 97px;
      height: 40px;

      display: flex;
      align-items: center;
      justify-content: center;

      background: #f1a3b8;
      box-shadow: 0 1px 5px 0 rgba(174, 174, 174, 0.47);
      border-radius: 8px;

      font-weight: 500;
      font-size: 16px;
      color: #fff;

      margin-right: 12px;
    }
  }
</style>

<style lang="less" scoped>
  .card {
    height: 100%;
    padding: 16px;

    .c-title {
      padding: 32px 0 6px 8px;
      color: #091f3d;
      font-size: 15px;
      font-weight: 600;
    }

    .c-title:first-child {
      padding-top: 8px;
    }
  }

  .cate-sub {
    position: relative;
    cursor: pointer;

    .cell {
      padding: 3px 12px;
      border-radius: 24px;
      font-size: 14px;
      font-weight: 400;
    }

    .tacit {
      border: 1px solid #e0e5ec;
      color: #091f3d;
    }

    .active {
      border: 1px solid @primary-color;
      background-color: @primary-color;
      color: #fff;
    }

    .btn {
      position: absolute;
      z-index: 2;
      right: 0;
      bottom: 0;
    }
  }

  .p-list {
    margin: 24px 0 0;

    .p-card {
      position: relative;
      margin: 12px 0;
      overflow: clip;
      border: 1px solid #e0e5ec;
      border-radius: 4px;

      .right {
        padding: 8px 32px 8px 0;

        .title {
          color: #091f3d;
          font-size: 14px;
        }

        .price {
          color: @primary-color;

          .value {
            font-size: 14px;
            letter-spacing: 1px;
          }

          .unit {
            padding-left: 2px;
            font-size: 10px;
          }
        }

        .desc {
          color: #acb4bf;
          font-size: 12px;
        }
      }

      .add {
        text-align: right;
        margin-top: 6px;
        margin-right: 6px;

        .icon {
          width: 25px;
          object-fit: contain;
        }
      }
    }

    .pagination {
      text-align: right;
      position: sticky;
      bottom: 0;
      background: #fff;
      z-index: 3;
      padding-top: 10px;
    }

    .active {
      border: 1px solid @primary-color;
    }
  }

  .jump_details {
    display: flex;
    .icon_jump_details {
      margin-top: -3px;
    }
  }

  .u-tabs {
    height: calc(100% - 46px);
    ::v-deep(.ant-tabs-content) {
      height: 100%;
    }
  }

  .list-search {
    width: 100%;
    .search-input {
      flex: 1;
      height: 46px;
      border-radius: 8px;
      font-size: 16px;
      color: #CED5DF;
    }
    .search-btn {
      height: 46px;
      width: 116px;
      font-size: 16px;
      font-weight: 500;
      border-radius: 8px;
    }
  }
</style>
